package main

import (
	"database/sql"
	"fmt"
	"github.com/sirupsen/logrus"
)

/*
 * @Author: XPectuer
 * @LastEditor: XPectuer
 */

type User struct {
	// UUid: from wechat Username
	Uuid      string
	NickName  string
	wordCount int64
}

func NewUser(uuid string, name string) *User {
	user := User{
		Uuid:      uuid,
		NickName:  name,
		wordCount: 0,
	}
	return &user
}

func NewUserFromDB(db *sql.DB, uuid string, name string) *User {
	
	user,err := QueryUserByUUID(db, uuid)
	if err != nil {
		if err == sql.ErrNoRows {
			user1 := NewUser(uuid, name)
			_, err := Insert(db, user1)
			if err != nil {
				logrus.WithError(err).Error("db error.")
			}

			return user1
		} else {
			logrus.WithError(err).Error("db error")
			return nil
		} 
	} else {
		return user
	}
}

func (user *User) AddWordCount(count int64) *User {
	user.wordCount += count
	return user
}

func (user *User) GetWordCount() int64 {
	return user.wordCount
}

func CountWords(msg string) int64 {
	return int64(len(msg))
}

func (user *User) String() string {
	return fmt.Sprintf("User{Uuid: %s, NickName: %s, wordCount: %d}", user.Uuid, user.NickName, user.wordCount)
}
